package com.hsy.sunflowerbao.base.action

import com.hsy.sunflowerbao.utils.CommonUtils

/**
 * Created on 2017/12/27.
 *
 * @author Yang
 */
open class BaseParam {

    /**
     *  把实体类转换成Map类
     */
    fun toMap(): Map<String, String> {
        val clazz = this::class.java
        val superClass = clazz.superclass

        val fields = clazz.declaredFields
        val superFields = superClass.declaredFields

        val params = if (CommonUtils.getToken() != "-1") mutableMapOf("token" to CommonUtils.getToken()) else mutableMapOf()

        if (fields == null || fields.isEmpty()) {
            return params
        }

        try {
            for (field in fields) {
                field.isAccessible = true

                if (field.get(this) != null) {
                    val key = field.name

                    if (field.get(this) != null) {
                        params.put(key, field.get(this).toString())
                    } else {
                        params.put(key, "null")
                    }
                }
            }

            for (superField in superFields) {
                superField.isAccessible = true

                if (superField.get(this) != null) {
                    val key = superField.name

                    if (superField.get(this) != null) {
                        params.put(key, superField.get(this).toString())
                    } else {
                        params.put(key, "null")
                    }
                }
            }
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        }

        return params
    }
}